package chat.server;

import java.io.IOException;

import chat.server.statemachine.termin.AlgorithmTermin;
import chat.server.statemachine.termin.TerminColor;
import chat.server.statemachine.termin.TerminTokenContent;

/**
 * Thread handling terminaison token
 * @author Baptiste Lafontaine
 *
 */
public class ChatServerTermin extends Thread {
	public int i = 0;
	ChatServerState sstate;

	/**
	 * Constructor starts the terminaison detection by sendind a token
	 * @param state
	 */
	public ChatServerTermin(ChatServerState state) {
		this.sstate = state;
		/* Starting terminate */
		System.out.println("Starting terminaison detection");
		TerminTokenContent ttc = new TerminTokenContent(TerminColor.WHITE,0);
		try {
			sstate.server.sendToAServer(sstate.getNext(), AlgorithmTermin.TERMIN_TOKEN_MESSAGE.getActionIndex(), ttc);
		} catch (IOException e) {
			System.out.println(sstate.identity + "::Error when starting terminaison detection while sending to " + sstate.getNext() + "(" + sstate.numOfNeigh + "neigh)");
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		do {
			System.out.println("Falling asleep...");

			/* Wait for a notity */
			try {
				sstate.TerminSemaphore.acquire();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			System.out.println("Waking up!");

			/* Wait for 2 sec */
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) { e.printStackTrace(); }

			/* Sendind token */
			System.out.println("2 sec elapsed, send new terminaison detection token");
			TerminTokenContent ttcsend = new TerminTokenContent(TerminColor.WHITE,0);
			try {
				sstate.server.sendToAServer(sstate.getNext(), AlgorithmTermin.TERMIN_TOKEN_MESSAGE.getActionIndex(), ttcsend);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} while (true);
	}
}
